package com.weareint.common.config;

import com.google.common.collect.Lists;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.autoconfigure.condition.ConditionalOnProperty;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import springfox.documentation.builders.ApiInfoBuilder;
import springfox.documentation.builders.PathSelectors;
import springfox.documentation.builders.RequestHandlerSelectors;
import springfox.documentation.builders.RequestParameterBuilder;
import springfox.documentation.oas.annotations.EnableOpenApi;
import springfox.documentation.service.Contact;
import springfox.documentation.service.ParameterType;
import springfox.documentation.spi.DocumentationType;
import springfox.documentation.spring.web.plugins.Docket;

@Configuration
@EnableOpenApi
@ConditionalOnProperty(prefix = "application", name = "swagger2.enable", havingValue = "true")
public class Swagger2Configuration {

    @Autowired
    private ApplicationProperties applicationProperties;

    @Bean
    public Docket createRestApi() {
        ApplicationProperties.Swagger2 swagger2 = applicationProperties.getSwagger2();
        ApplicationProperties.Swagger2.Contact contact = swagger2.getContact();
        return new Docket(DocumentationType.SWAGGER_2)
                .enable(swagger2.isEnable())
                .forCodeGeneration(true)
                .operationOrdering((o1, o2) -> null == o1.getSummary() || null == o2.getSummary()
                        ? 0 : o1.getSummary().compareTo(o2.getSummary()))
                .globalRequestParameters(Lists.newArrayList(
                        new RequestParameterBuilder()
                                .name("Authorization")
                                .description("Token")
                                .required(false)
                                .in(ParameterType.HEADER)
                                .hidden(false)
                                .parameterIndex(0)
                                .build()
                ))
                .useDefaultResponseMessages(false) // 默认不再显示各个Http状态码的Response，只显示200的状态码
                .apiInfo(new ApiInfoBuilder()
                        .title(swagger2.getTitle())
                        .description(swagger2.getDescription())
                        .version(swagger2.getVersion())
                        .contact(new Contact(contact.getName(), contact.getUrl(), contact.getEmail()))
                        .build())
                .select()
                //过滤掉 其他的
                .apis(RequestHandlerSelectors.basePackage("com.weareint.biz.controller"))
                .paths(PathSelectors.any())
                .build();
    }

}
